<script setup lang="ts" >
import router from '@/router';
import type { Datum, PostParkAddEnterpriseParams } from '@/types/enterprise';
import { PostUploadAPI } from '@/utils/commen';
import { GetParkIndustryAPI, PostParkAddEnterpriseAPI, GetParkAddEnterpriseParamsAPI, PutParkEnterpriseParamsAPI } from '@/utils/enterprise';
import { CircleCheck, Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref } from 'vue';
import { useRoute } from 'vue-router';

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<PostParkAddEnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId:  undefined// 营业执照id
}) 

// 列表数组
const ParkIndustryList = ref<Datum[]>([])
// 查询企业行业列表
const GetParkIndustry  = async ()=>{
  const res = await GetParkIndustryAPI()

  ParkIndustryList.value = res.data
}

GetParkIndustry()
// 文件上传之前的业务

const beforeUpload = (file: UploadRawFile)=>{
  const allowImageType = ['image/jpeg','image/jpg','image/png'].includes(file.type)
  const limitSize = file.size / 1024 / 1024 < 5
  if(!allowImageType){
    ElMessage.error('上传的图片格式只能是JPG/JPEG/PNG！')
  }
  if(!limitSize){
    ElMessage.error('上传的文件大小不能超过5M！')
  }
  return allowImageType && limitSize

}

// 营业执照列表
const fileList = ref<UploadUserFile[]>([])
// 自定义上传请求
const onUploadRequest = async(options: UploadRequestOptions) =>{
  // console.log('options',options)
  // 1.准备formData 对象
  const fd = new FormData()
  // 2.根据后端要求准备字段
  fd.append('file',options.file)
  fd.append('type','businessLicense')
  // 3.调用接口上传文件
  const res = await PostUploadAPI(fd)
  // 保存营业执照url和id
  addForm.value.businessLicenseId = res.data.id
  addForm.value.businessLicenseUrl = res.data.url
  // 主动触发校验
  FormRef.value?.validateField('businessLicenseUrl')
  // 4.检查上传结果
  // console.log(res);
  
  // 图片路径存储到 数组的response中
  return res.data.url
}



const formRules = ref<FormRules<PostParkAddEnterpriseParams>>(
  {
    name:[
      { required:true,message:'请输入企业名称',trigger:'blur' },
    ],
    legalPerson:[
      { required:true, message:'请输入企业法人',trigger:'blur'},
    ],
    registeredAddress:[
      { required:true, message:'请输入注册地址',trigger:'blur'}
    ],
    industryCode:[
      { required:true, message:'请输入所在行业',trigger:'change'}
    ],
    contact:[
    { required:true, message:'请输入企业联系人',trigger:'blur'}
    ],
    contactNumber:[
    { required:true, message:'请输入企业联系方式',trigger:'blur'},
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: 'blur' },
    ],
    businessLicenseUrl:[
      { required:true, message:'请上传营业执照',trigger:'blur'}
    ]
  }
)
// 获取整个表单
const FormRef = ref<FormInstance>()
// 加载中状态
const SubmitLoading  = ref(false)


// 确定添加企业业务
const addEnterprise = async() =>{

  try{
  // 发送数据请求前，先进行校验
  const valid = await  FormRef.value?.validate()
  console.log(route.params);

    // 把表单设置为禁用状态避免弱网络时重复提交
    SubmitLoading.value = true
    if(valid){
      // 如果校验通过，根据id发送请求添加/修改企业
      
      
      if(route.params.id){
       
        // 编辑业务
       const res = await PutParkEnterpriseParamsAPI({
          id:route.params?.id ,
          ...addForm.value
        })
        console.log('编辑业务',res);
        
      }else{
        // 添加业务
       const res =  await PostParkAddEnterpriseAPI(addForm.value)
        console.log('添加业务',res)
      }
     
    
    //  轻提示
      ElMessage.success(route.params.id ? '编辑成功':'添加成功')
      router.back()
    }

  }catch(error){
    console.error(error);
    SubmitLoading.value = false
  }

 
}

// 重置表单

const onReset = () =>{
  FormRef.value?.resetFields()
}

// 删除营业执照
const removeUpload = () =>{
addForm.value.businessLicenseId = undefined
addForm.value.businessLicenseUrl = ''
// 删除之后再单独校验表单
FormRef.value?.validateField('businessLicenseUrl')
}

// 回填企业数据
const EditEnterprise =  async() =>{
  const res = await GetParkAddEnterpriseParamsAPI(route.params.id as string)
  console.log('回填企业数据',res)
  const { name,legalPerson,registeredAddress,industryCode,contact,contactNumber,businessLicenseUrl,businessLicenseId }  = res.data
  addForm.value.name = name
  addForm.value.legalPerson = legalPerson
  addForm.value.registeredAddress = registeredAddress
  addForm.value.industryCode = industryCode
  addForm.value.contact = contact
  addForm.value.contactNumber = contactNumber
  addForm.value.businessLicenseUrl = businessLicenseUrl
  addForm.value.businessLicenseId = businessLicenseId
  // 营业执照
  fileList.value = [
    {name:'file',url:businessLicenseUrl}
  ]
}

// 获取路由参数
const route = useRoute()
// 如果路由有id，调用请求回填表单数据
if(route.params.id){
  EditEnterprise()
}


</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id ? '编辑企业' :'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="FormRef" label-width="100px" :model="addForm" :rules="formRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode"  >
              <el-option v-for=" item in ParkIndustryList" 
              :key="item.industryCode"
              :value="item.industryCode"
              :label="item.industryName"
              ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
            <el-upload action="#" 
            @remove="removeUpload"
             :http-request="onUploadRequest"
             :limit="1"
             v-model:file-list="fileList"
             :before-upload="beforeUpload"
              accept=".png, .jpg, .jpeg"
              list-type="picture-card"
             >
              <el-button v-if="fileList.length === 0" type="primary" :icon="Upload">上传文件</el-button>
              <el-button v-else type="success" :icon="CircleCheck" disabled>已上传</el-button>
                <template>

                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="addEnterprise" :loading="SubmitLoading">
          {{ SubmitLoading ? '提交中' : '确定' }}</el-button>
      
      </div>
      {{ addForm }}
    </footer>
    
  </div>
  
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    /* 移除或注释掉不必要的样式 */
    // .left {
    //   span {
    //     margin-right: 4px;
    //   }

    //   .arrow {
    //     cursor: pointer;
    //   }
    // }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>